package com.xzq.wanandroid.base.modle;

import android.os.Build;
import android.text.TextUtils;

import androidx.annotation.RequiresApi;

import com.blankj.utilcode.util.SPUtils;
import com.xzq.wanandroid.API.ApiAdress;
import com.xzq.wanandroid.API.ApiService;

import java.io.IOException;
import java.util.List;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @ClassName : BaseModle
 * @Description : 基础Modle类里包含了初始化配置好的一些网络请求
 * @Author : xzq
 * @Date: 2021-05-08 15:28
 * @Version :
 */
public class BaseModle {

    protected Retrofit retrofit;
    protected ApiService apiService;

    public void BaseModle() {
        retrofit = new Retrofit.Builder()
                .baseUrl(ApiAdress.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create()).
                        build();
        apiService = retrofit.create(ApiService.class);
    }

    /**
     * 设置是否保存Cookie
     */

    public void setCookies(boolean isSaveCookies) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new ReadCookieInterceptor());
        builder.addInterceptor(new WriteCookieInterceptor(isSaveCookies));
        retrofit = new Retrofit.Builder()
                .client(builder.build())
                .baseUrl(ApiAdress.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create()).
                        build();
        apiService = retrofit.create(ApiService.class);
    }


    private class ReadCookieInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            Request.Builder builder = chain.request().newBuilder();
            long expire = SPUtils.getInstance("cookie").getLong("cookie_expire", 0);//取出存储的cookie时间判断是否过期
            if (expire > System.currentTimeMillis()) {
                String cookies = SPUtils.getInstance("cookie").getString("user");
                if (!TextUtils.isEmpty(cookies)) {
                    for (String cookie : cookies.split(";")) {
                        builder.addHeader("Cookie", cookie);
                    }
                    return chain.proceed(builder.build());
                }
            }
            return response;
        }
    }

    private class WriteCookieInterceptor implements Interceptor {
        private boolean saveCookie;

        public WriteCookieInterceptor(boolean saveCookie) {
            this.saveCookie = saveCookie;
        }

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            if (saveCookie) {
                List<String> headers = response.headers("Set-Cookie");
                if (!headers.isEmpty()) {
                    StringBuffer sb = new StringBuffer();
                    headers.stream().forEach(h -> sb.append(h).append(";"));
                    SPUtils.getInstance("cookie").put("user", sb.toString());
                    SPUtils.getInstance("cookie").put("cookie_expire", System.currentTimeMillis() + 30 * 24 * 3600 * 1000L);//设置一个月的有效时间
                }
            }
            return response;
        }
    }
}


